import axios from 'axios'
import {Toast} from 'vant'


axios.defaults.baseURL = 'https://api.roborock.com/v2/';

export {axios}

function ShowLoading(msg = "加载中...") {
  Toast.clear()
  Toast.loading({
    forbidClick: true,
    message: msg,
  });
}

function ShowError(msg = "未知错误") {
  Toast.clear()
  Toast.fail(msg);
}

// function ShowSuccess(msg = "成功") {
//   Toast.clear()
//   Toast.success(msg);
// }

// axios 请求拦截器
axios.interceptors.request.use(function (config) {
  ShowLoading()
  return config;
}, function (error) {
  ShowError('请求失败')
  return Promise.reject(error);
});

// axios 响应拦截器
axios.interceptors.response.use(function (response) {
  Toast.clear()
  return response;
}, function (error) {
  ShowError('响应失败')
  return Promise.reject(error);
});


// GET
export const get = function (url, params, headers) {
  return new Promise(function (resolve, reject) {
    axios({
      url,
      method: "GET",
      params,
      headers
    })
      .then(res => {
        resolve(res.data) // 返回数据
      })
      .catch(err => {
        reject(err) // 返回错误
      })
  })
}
// POST
export const post = function (url, data, headers) {
  return new Promise(function (resolve, reject) {
    axios({
      url,
      method: "POST",
      data,
      headers
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
// PATCH
export const Patch = function (url, data, headers) {
  return new Promise(function (resolve, reject) {
    axios({
      url,
      method: "PATCH",
      data,
      headers
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
// DELETE
export const Delete = function (url) {
  return new Promise(function (resolve, reject) {
    axios({
      url,
      method: "DELETE",
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
